package com.linkoog.devtools.dubbo.persistent;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.linkoog.devtools.dubbo.toolwindow.environment.DubboEnvironment;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

@State(name = "DubboEnvironment", storages = { @Storage("dubbo-environment.settings.xml") })
public class DubboEnvironmentPersistent implements PersistentStateComponent<DubboEnvironmentPersistent> {

    private List<DubboEnvironment> dubboEnvironments;


    public DubboEnvironmentPersistent() {
    }

    public static DubboEnvironmentPersistent getInstance(){
        return ApplicationManager.getApplication().getService(DubboEnvironmentPersistent.class);
    }

    @Override
    public DubboEnvironmentPersistent getState() {
        return this;
    }

    @Override
    public void loadState(@NotNull final DubboEnvironmentPersistent state) {
        XmlSerializerUtil.copyBean(state, this);

    }

    private DubboEnvironment createDefaultEnvironment(){
        DubboEnvironment env = new DubboEnvironment();
        env.setName("default");
        env.setProtocol("dubbo");
        env.setIp("127.0.0.1");
        env.setPort(20880);
        return env;
    }



    /*-------------------------------------------------------------------------------------------------------------------*/

    public List<DubboEnvironment> getDubboEnvironments() {
        if (dubboEnvironments == null) {
            dubboEnvironments = new ArrayList<>();
        }
        if (dubboEnvironments.isEmpty()){
            dubboEnvironments.add(createDefaultEnvironment());
        }
        return dubboEnvironments;
    }

    public void setDubboEnvironments(List<DubboEnvironment> dubboEnvironments) {
        this.dubboEnvironments = dubboEnvironments;
    }
}
